<template>
  <div class="friend-friends-container">
    <div class="friend-list-area">
      <!-- 搜索框 -->
      <el-input
        placeholder="搜索"
        prefix-icon="el-icon-search"
        style="width: 100%; margin: 10px 0;"
      >
        <template slot="append">
          <el-button icon="el-icon-plus" circle @click="upSearchUserDialog"></el-button>
        </template>
      </el-input>

      <!-- 好友列表 -->
      <ul class="friend-items">
        <li class="friend-item"
            :class="{ active: 'newFriend' === activeItemId }"
            @click="getFriendInfo({userId: 'newFriend',userName: '新的朋友'},'friend-list')">
          <el-avatar style="margin-left: 0.2vw" :size="32" src="https://example.com/family.jpg" />
          <div class="friend-info">
            <p class="name">新的朋友</p>
          </div>
        </li>
        <li class="friend-item"
            :class="{ active: item.userId === activeItemId }"
            v-for="item in friendList"
            :key=item.userId
            @click="getFriendInfo(item,'friend-list')">
          <el-avatar style="margin-left: 0.2vw" :size="32" src="https://example.com/family.jpg" />
          <div class="friend-info">
              <p class="name">{{item.userName}}</p>
          </div>
        </li>
      </ul>
    </div>

    <div class="friend-window">
      <!-- 标题栏 -->
      <div class="window-title-bar">
        <div>
          <span class="group-title">{{targetFriend.userName}}</span>
        </div>
      </div>
      <!--  内容    -->
      <div class="" v-if="isShowFriendApply">
        <ul class="friend-items" v-if="friendApplyList && friendApplyList.length > 0">
          <li class="friend-item"
              :class="{ active: item.userId === activeItemId }"
              v-for="item in friendApplyList"
              :key="item.requestId">
            <el-avatar style="margin-left: 0.2vw" :size="32" :src="item.avatar || '../../images/default.webp'"></el-avatar>
            <div class="friendApply-info">
              <div>
                <p class="name" v-if="item.senderId === curUserId">{{item.receiver}}</p>
                <p class="name" v-else>{{item.sender}}</p>
                <p class="apply-desc" v-if="item.senderId === curUserId">{{friendRequest.message}}</p>
                <p class="apply-desc" v-else>申请添加你为好友</p>
              </div>

              <div class="apply-ops" v-if="item.senderId === curUserId">
                <el-button disabled size="mini" v-if="item.status === 0">{{item.statusStr}}</el-button>
                <el-button disabled size="mini" v-else>已{{item.statusStr}}</el-button>
              </div>
              <div class="apply-ops" v-else>
                <div v-if="item.status === 0">
                  <el-button type="primary" size="mini" @click.stop="handleFriendRequest(item.requestId,item,1)">同意</el-button>
                  <el-button size="mini" @click.stop="handleFriendRequest(item.requestId,item,2)">拒绝</el-button>
                </div>
                <div v-else>
                  <el-button disabled size="mini">已{{item.statusStr}}</el-button>
                </div>
              </div>
            </div>
          </li>
        </ul>
        <div v-else>
          <p class="no-friend-apply">暂无好友申请</p>
        </div>
      </div>
      <!-- 好友信息区域（红框位置） -->
      <div class="friend-info-content" v-else-if="friendInfo.flag !== null">
        <el-card class="friend-card">
          <el-avatar slot="header" :size="80" :src="friendInfo.avatar || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'"></el-avatar>
          <div class="friend-info-detail">
            <h3>{{ friendInfo.userName }}</h3>
            <p><el-tag type="info">ID: {{ friendInfo.userId }}</el-tag></p>
            <p><el-tag type="success">状态: {{ friendInfo.online === true ? '在线' : '离线' }}</el-tag></p>
            <p class="friend-desc">{{ friendInfo.desc || '这个人很懒，没有留下签名～' }}</p>
            <div class="friend-ops">
              <el-button type="primary" icon="el-icon-message" @click="goChat(friendInfo)">发消息</el-button>
              <el-button icon="el-icon-setting">设置</el-button>
            </div>
          </div>
        </el-card>
      </div>
    </div>


    <el-dialog title="添加好友" :visible.sync="isShowSearchUserDialog" width="700px" append-to-body>
      <!-- 搜索框 -->
      <el-input
        placeholder="手机号/姓名"
        prefix-icon="el-icon-search"
        style="width: 100%; margin: 10px 0;"
        v-model="userQueryVO.searchUserKey"
      >
        <template slot="append">
          <el-button icon="el-icon-search" circle @click="searchUser()"></el-button>
        </template>
      </el-input>
      <div class="search-list-area">
        <div class="search-friend-list">
          <!-- 好友列表 -->
          <ul class="friend-items">
            <li class="friend-item"
                :class="{ active: item.userId === activeFriendId }"
                v-for="item in searchUserList"
                :key=item.id
                @click="getFriendInfo(item,'search-list')">
              <el-avatar style="margin-left: 0.2vw" :size="32" :src="item.avatar" />
              <div class="friend-info">
                <p class="name">{{item.userName}}</p>
              </div>
            </li>
          </ul>
        </div>
        <div class="search-friend-info">
          <div class="friend-card">
            <div class="card-header">
              <el-avatar
                :size="60"
                :src="selectedFriend.avatar"
              />
              <div class="header-info">
                <h3 class="friend-name">{{ selectedFriend.userName }}</h3>
                <p class="friend-desc" v-if="selectedFriend.signature">
                  {{ selectedFriend.signature }}
                </p>
              </div>
            </div>
            <div class="card-body">
              <div class="info-item">
                <span class="label">ID：</span>
                <span class="value">{{ selectedFriend.userId }}</span>
              </div>
              <div class="info-item">
                <span class="label">性别：</span>
                <span class="value">{{ selectedFriend.sex || '未知' }}</span>
              </div>
              <div class="info-item">
                <span class="label">地区：</span>
                <span class="value">{{ selectedFriend.region || '未设置' }}</span>
              </div>
              <div class="info-item">
                <span class="label">个性签名：</span>
                <span class="value">{{ selectedFriend.signature || '暂无签名' }}</span>
              </div>
              <div class="info-item">
                <span class="label">打招呼内容：</span>
                <el-input style="width: 100%; margin: 10px 0;" type="textarea" rows="3" placeholder="请输入打招呼内容" v-model="friendRequest.message"></el-input>
              </div>
              <div class="info-item">
                <span class="label">备注：</span>
                <el-input
                  placeholder="备注"
                  style="width: 100%; margin: 10px 0;"
                  v-model="friendRequest.remark"
                ></el-input>
              </div>
            </div>
            <div class="card-footer">
              <!-- 查询当前用户是否添加，添加的话，显示发消息，没有添加的话，显示添加   -->
              <el-button :disabled="selectedFriend.friendStatus !== null && selectedFriend.friendStatus === 0 ? true : false"
                         @click="selectedFriend.friendStatus !== null && selectedFriend.friendStatus === 1 ? goChat(selectedFriend) : addFriend() "
                         type="primary" size="small">
                {{isShowAddFriText}}
              </el-button>
            </div>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="downSearchUserDialog">关 闭</el-button>
      </div>
    </el-dialog>

  </div>



</template>
<script>
import { addFriendApi,searchUserApi,getFriendListApi,getOneFriendRequestApi,getFriendApplyListApi,handleFriendRequestApi,createChatSessionApi } from "@/api/system/chat"
import user from "@/store/modules/user";

export default {
  data() {
    return {
      curUserId:user.state.id,
      activeItemId: null,
      activeFriendId:null,
      friendList:[
        // this.newFriendItem,
      ],
      newFriendItem:{
        userId:'newFriend',
        name:'新的朋友',
        avatar:'https://example.com/avatar.jpg',
      },
      friendRequest:{
        message:'我是'+user.state.name,
        senderId: user.state.id,
        receiverId: '',
        remark: null
      },
      isShowSearchUserDialog:false,
      searchUserList:[],
      selectedFriend:{
        flag:null,  // 判断是否已选择好友  null 没有选择   true 已选择
      },
      targetFriend:{},
      isShowFriendApply:false,
      friendInfo: {
        flag:null,  // 判断是否已选择好友  null 没有选择   true 已选择
      },
      friendApplyList:[],
      isShowAddFriText:'添加',
      userQueryVO:{
        searchUserKey:null,
        userId:null,
        avatar:null,
        deptId:null,
        userName:null,
        nickName:null,
        email:null,
        phonenumber:null,
        sex:null,
        pageNum:1,
        pageSize:10
      }
    }
  },
  mounted() {
    // 获取缓存的用户信息
    let userId = user.state.id;
    this.getFriendList(userId);
  },
  methods: {
    getFriendInfo(item,opsStr){
      // TODO 获取好友信息
      if (opsStr.match('friend-list')){
        // 好友列表-选中
        this.activeItemId = item.userId
        Object.assign(this.targetFriend,item);
        if(item.userId === 'newFriend'){
          this.isShowFriendApply = true
          this.getFriendApplyList(user.state.id);
        }else {
          // 设置好友信息
          this.isShowFriendApply = false
          this.friendInfo.flag =  true
          Object.assign(this.friendInfo,item);
        }
      }else if (opsStr.match('search-list')){
        // 添加好友对话框--搜索后的好友列表-选中
        this.activeFriendId = item.userId
        this.selectedFriend.flag = true
        this.friendRequest.remark = item.userName
        Object.assign(this.selectedFriend,item);
        this.isShowAddFriText = item.friendStatusText
      }
    },
    addFriend(){
      if(this.selectedFriend.flag === null){
        this.$message.warning('请选择好友');
        return
      }
      // TODO 添加好友
      this.friendRequest.receiverId = this.selectedFriend.userId;
      let saveJson = JSON.stringify(this.friendRequest);
      addFriendApi(saveJson).then(response => {
        console.log("@@@ FriendListPage.vue addFriendApi",response);
        if(response.code === 200){
          this.$message.success('添加成功');

          // 根据条件，获取申请单
          let obj = {senderId: user.state.id, receiverId: this.selectedFriend.userId}
          this.getOneFriendRequest(obj)
          this.getFriendApplyList(user.state.id)
          this.downSearchUserDialog()

        }else{
          this.$message.error('添加失败');
        }
      })
    },
    getOneFriendRequest(item){
      // TODO
      let queryJson = JSON.stringify(item);
      getOneFriendRequestApi(queryJson).then(response => {
        console.log("@@@ FriendListPage.vue getOneFriendRequestApi",response);
        if(response.code === 200){
          this.isShowAddFriText = response.data.statusStr
        }
      })
    },
    searchUser(){
      // TODO 搜索用户
      this.selectedFriend = {
        flag:null,
      }
      if(this.userQueryVO.searchUserKey === null){
        return
      }
      this.userQueryVO.userId = user.state.id;
      let userQueryJson = JSON.stringify(this.userQueryVO);
      searchUserApi(userQueryJson).then(response => {
        this.searchUserList = response.data;
      })
    },
    getFriendList(userId){
      let obj = {userId: userId}
      let queryJson = JSON.stringify(obj);
      getFriendListApi(queryJson).then(response => {
        this.friendList = response.data;
      })
    },
    // 获取好友申请列表
    getFriendApplyList(userId){
      let obj = {curUserId: userId}
      let queryJson = JSON.stringify(obj);
      getFriendApplyListApi(queryJson).then(response => {
        console.log("@@@ FriendListPage.vue getFriendApplyListApi",response);
        this.friendApplyList = response.data;
      })
    },
    upSearchUserDialog(){
      this.isShowSearchUserDialog = true
    },
    downSearchUserDialog(){
      this.isShowSearchUserDialog = false

      this.searchUserList = []
      this.userQueryVO.searchUserKey = ''
    },
    handleFriendRequest(requestId,item,status){
      let obj = {requestId: requestId, status: status,receiverId: item.receiverId,senderId: item.senderId}
      let queryJson = JSON.stringify(obj);
      handleFriendRequestApi(queryJson).then(response => {
        console.log("@@@ FriendListPage.vue handleFriendRequestApi",response);
        this.getFriendApplyList(user.state.id);
        if(status === 1){
          this.getFriendList(user.state.id);
        }
      })
    },
    routerToChatPage(page){
      // 跳转到聊天页面
      // this.$emit('child-event', page);
      this.$parent.handleChildEvent(page)
    },
    createChatSession(friendInfo){
      // 创建会话
      let obj = {
        friendInfo:friendInfo,
        userId: user.state.id,
        conversationType: 1 ,
      }
      let queryJson = JSON.stringify(obj);
      createChatSessionApi(queryJson).then(response => {
        console.log("@@@ FriendListPage.vue createChatSessionApi",response);

      })
    },
    goChat(friendInfo){
      this.createChatSession(friendInfo)
      this.$emit('go-chat', friendInfo)
    }
  }
}


</script>
<style scoped>
.friend-friends-container {
  height: 92vh;
  display: flex;
  width: 100%;
}

.friend-list-area {
  width: 240px;
  border-right: 1px solid #e5e5e5;
  display: flex;
  flex-direction: column;
  padding: 10px;
}


.friend-items {
  list-style: none;
  padding: 0;
  margin: 0;
  flex: 1;
  overflow-y: auto;
}

.friend-item {
  display: flex;
  align-items: center;
  padding: 8px 0;
  cursor: pointer;
}

.friend-item:hover {
  background-color: #f5f5f5;
}

.friend-item.active {
  background-color: #e5e5e5;
}

.friend-info {
  margin-left: 8px;
  width: 100%;
  font-weight: bold;
  font-size: 15px;

}

.friendApply-info{
  margin-left: 8px;
  width: 100%;
  font-weight: bold;
  font-size: 15px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}


.name {
  margin: 0; /* 去除 p 标签默认的外边距，使布局更规整 */
}

.empty-tip {
  text-align: center;
  color: #999;
  padding: 20px;
}

.apply-desc {
  color: #666;
  font-size: 12px;
  margin: 5px 0;
}
.apply-ops {
  margin-top: 5px;
  margin-right: 5px;
}


.search-list-area {
  display: flex;
  padding: 20px;
  box-sizing: border-box;
}


.search-friend-list {
  width: 280px;
  border-right: 1px solid #eaeaea;
  overflow-y: auto;
}

.search-friend-info {
  flex: 1;
  padding: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.friend-card {
  width: 360px;
  border: 1px solid #eaeaea;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  margin: 0 auto;
}

.card-header {
  padding: 24px;
  background-color: #fafafa;
  display: flex;
  align-items: center;
}

.header-info {
  margin-left: 16px;
}

.friend-name {
  font-size: 18px;
  margin: 0 0 8px 0;
}

.friend-desc {
  font-size: 14px;
  color: #666;
  margin: 0;
}

.card-body {
  padding: 24px;
}

.info-item {
  margin-bottom: 16px;
  display: flex;
  align-items: center;
}

.label {
  width: 80px;
  color: #888;
}

.value {
  flex: 1;
}

.card-footer {
  padding: 16px 24px;
  background-color: #fafafa;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}


.friend-window{
  flex: 1;
  display: flex;
  flex-direction: column;
}
.window-title-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px;
  border-bottom: 1px solid #e5e5e5;
}

.group-title {
  font-size: 18px;
  margin-right: 10px;
}

.no-friend-apply {
  /* 文字样式 */
  font-family: "Microsoft Yahei", sans-serif;
  font-size: 14px;
  color: #666;
  text-align: center;

  /* 间距与布局 */
  padding: 20px 0;
  margin: 0; /* 移除默认外边距 */
  line-height: 1.6; /* 增加行高提升可读性 */
}

/* 单独写伪元素样式 */
.no-friend-apply::before {
  content: "📭 ";
  font-size: 20px;
  margin-right: 5px;
}

/* 单独写hover样式 */
.no-friend-apply:hover {
  color: #333;
  transition: color 0.3s ease; /* 增加过渡动画更平滑 */
}

.friend-ops{
  margin-top: 15px;
}

.friend-info-content{
  padding: 20px;
}

</style>
